package com.example.demo.service;

import com.example.demo.model.Books;

import com.example.demo.repository.BooksRepository;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.data.domain.Page;

import org.springframework.data.domain.PageRequest;

import org.springframework.data.domain.Pageable;

import org.springframework.data.domain.Sort;

import org.springframework.stereotype.Service;

import java.util.List;

import java.util.Optional;
@Service
public class BooksServiceImpl implements BooksService {
    @Autowired
    private BooksRepository bookRepository;
    @Override
    public List<Books> getAllBook() {
        return bookRepository.findAll();
    }
    @Override
    public void addBook(Books book) {

        this.bookRepository.save(book);
    }
    @Override
    public void updateBook(Books book) {
        bookRepository.saveAndFlush(book);
    }
    @Override
    public Books getBookById(long id) {
        //查找指定id，返回Optional对象
        Optional<Books> optional = bookRepository.findById(id);
        Books book = null;
        if (optional.isPresent()){  //如果id存在
            book = optional.get();  //从Optional对象中获取图书
        }else {
            throw new RuntimeException("找不到图书id :" + id);
        }
        return book;
    }
    @Override
    public void deleteBookById(long id) {
        this.bookRepository.deleteById(id);
    }
    @Override
    public Page<Books> findPaginated(int pageNo, int pageSize, String sortField,
                                     String sortDirection) {
        Sort sort = sortDirection.equalsIgnoreCase(Sort.Direction.ASC.name())
                ? Sort.by(sortField).ascending()
                : Sort.by(sortField).descending();
        Pageable pageable = PageRequest.of(pageNo - 1,pageSize, sort);
        return this.bookRepository.findAll(pageable);
    }
    @Override
    public Books findByAuthor(String author) {
        return (Books) bookRepository.findByAuthor(author);
    }

}







